var express = require('express');
var router = express.Router();
const { User } = require('../../models');
const { Op } = require('sequelize');
const { successResponse, failureResponse } = require('../../utils/responses')

router.get('/', async function(req, res, next) {
  try {
    const { email, username, nickname, role } = req.query;
    const currentPage = parseInt(req.query.currentPage) || 1; // 当前页码，默认为 1
    const pageSize = parseInt(req.query.pageSize) || 10; // 每页数量，默认为 10
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      order: [['id', 'DESC']], // 按照 id 降序排列
      limit: pageSize,
      offset: offset,
      where: {}
    }
    if (email) {
      condition.where.email = email
    }
    if (username) {
      condition.where.username = username
    }
    if (nickname) {
      condition.where.nickname = {
        [Op.like]: `%${nickname}%`
      }
    }
    if (role) {
      condition.where.role = role
    }
    // 查询所有用户
    const { rows, count } = await User.findAndCountAll(condition)
    res.json({
      status: true,
      message: 'user route',
      data: {
        users: rows,
        pagination: {
          pageSize,
          currentPage,
          total: count
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch users',
      error: [error.message]
    });
  }
});

router.get('/:id', async function(req, res, next) {
  try {
    const { id } = req.params;
    // 查询主键 id 的用户
    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        status: false,
        message: 'User not found',
      });
    }
    res.json({
      status: true,
      message: 'User fetched successfully',
      data: {
        user
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch user',
      error: [error.message]
    });
  }
})

// 查询当前登录的用户信息
router.get('/me', async function(req, res, next) {
  try {
    successResponse(res, '查询当前用户信息成功', { user: req.user })
  } catch (error) {
    failureResponse(res, error)
  }
})

router.post('/', async function(req, res, next) {
  try {
    const user = await User.create(filterBody(req.body));
    res.status(201).json({
      status: true,
      message: 'User created successfully',
      data: {
        user
      }
    });
  } catch (error) {
    if (error.name === 'SequelizeValidationError') {
      return res.status(400).json({
        status: false,
        message: '请求参数错误',
        error: error.errors.map(err => err.message)
      });
    } else {
      res.status(500).json({
        status: false,
        message: 'Failed to create user',
        error: [error.message]
      });
    }
  }
})

router.put('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        status: false,
        message: 'User not found',
      });
    }
    await user.update(filterBody(req.body));
    res.json({
      status: true,
      message: 'User update successfully',
      data: {
        user
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to update user',
      error: [error.message]
    });
  }
})

function filterBody(body) {
  const {
    email, username, password,
    nickname, sex, company,
    introduce, role, avatar,
  } = body;
  return {
    email,
    username,
    password,
    nickname,
    sex,
    company,
    introduce,
    role,
    avatar
  };
}

module.exports = router;
